package com.example.lowbird.lowbird.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lowbird.lowbird.R;
import com.example.lowbird.lowbird.app.Myapp;
import com.example.lowbird.lowbird.bean.LoginBean;
import com.example.lowbird.lowbird.constant.Contants;
import com.example.lowbird.lowbird.utils.CountTimerView;
import com.example.lowbird.lowbird.utils.DESUtil;
import com.example.lowbird.lowbird.utils.SpUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.UserInterruptException;
import cn.smssdk.utils.SMSLog;
import okhttp3.Call;

import static com.mob.tools.utils.R.getStringRes;


public class LoginActivity2 extends AppCompatActivity {
    private SMSeventhandler smSeventhandler;
    private Context mContext;
    private Button bt_mycomplete;
    private TextView tv_phonenumber;
    private Button bt_repost;
    private String phone;
    private String password;
    private String code;
    private EditText et_vcode;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    private CountTimerView cv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login2);
        SMSSDK.initSDK(this, "18c71cb44fc66", "b8d168de9f126045ddfaa7f8fdbb09b4");


        Intent intent = getIntent();

        if (intent != null) {
            phone = intent.getStringExtra("phone");
            password = intent.getStringExtra("password");

            code = intent.getStringExtra("code");

        }

        mContext = this;
        smSeventhandler = new SMSeventhandler();

        SMSSDK.registerEventHandler(smSeventhandler);
        initview();
         cv = new CountTimerView(bt_repost);
        cv.start();

    }

    private void initview() {

        bt_mycomplete = ((Button) findViewById(R.id.bt_mycomplete));
        bt_mycomplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                regmessage();
            }
        });
        et_vcode = ((EditText) findViewById(R.id.et_vcode));

        tv_phonenumber = ((TextView) findViewById(R.id.tv_phonenumber));
        tv_phonenumber.setText(phone);
        bt_repost = (Button) findViewById(R.id.bt_repost);
        bt_repost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SMSSDK.getVerificationCode(code, phone);
                cv.start();


            }
        });

    }

    private void regmessage() {


        String trim = et_vcode.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {

            Log.e("LOG", "请输入验证码 ");

            return;
        }
        Log.e("LOG", "code: "+code );

        SMSSDK.submitVerificationCode(code, phone, trim);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(smSeventhandler);
    }





    class SMSeventhandler extends EventHandler {

        @Override
        public void afterEvent(final int event, final int result,
                               final Object data) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {


                    if (result == SMSSDK.RESULT_COMPLETE) {
                        if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {

                            Log.e("LOG", "验证成功 啦 ");

                            Map<String, String> params = new HashMap<>(2);
                            params.put("phone", phone);
                            params.put("password", DESUtil.encode(Contants.DES_KEY,password));

                            OkHttpUtils.post().url(Contants.API.REG).params(params).build().execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {




                                }

                                @Override
                                public void onResponse(String response, int id) {

                                    String string = response.toString();

                                    LoginBean loginBean = new Gson().fromJson(string, LoginBean.class);


                                    if (loginBean.getStatus()==1){

                                        //注册成功,跳转到主界面

                                        {

                                            Intent intent = new Intent(mContext, MainActivity.class);
                                            SpUtil.putString(mContext, phone, string);
                                            intent.putExtra("loginBean", loginBean);
                                            mContext.startActivity(intent);

                                            finish();
                                        }



                                    }else {
                                        Log.e("LOG", "onResponse: 注册失败" );
                                        Toast.makeText(mContext,"注册失败",Toast.LENGTH_SHORT).show();

                                        Intent intent=new Intent(mContext,LoginActivity.class);
                                        mContext.startActivity(intent);

                                        finish();


                                    }




                                }
                            });

                        }
                    } else {
                        if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE
                                && data != null
                                && (data instanceof UserInterruptException)) {
                            // 由于此处是开发者自己决定要中断发送的，因此什么都不用做
                            return;
                        }

                        // 根据服务器返回的网络错误，给toast提示
                        try {
                            ((Throwable) data).printStackTrace();
                            Throwable throwable = (Throwable) data;

                            JSONObject object = new JSONObject(
                                    throwable.getMessage());
                            String des = object.optString("detail");
                            if (!TextUtils.isEmpty(des)) {

                                return;
                            }
                        } catch (Exception e) {
                            SMSLog.getInstance().w(e);
                        }
                        // 如果木有找到资源，默认提示
                        int resId = getStringRes(mContext,
                                "smssdk_network_error");
                        if (resId > 0) {
                            Toast.makeText(mContext, resId, Toast.LENGTH_SHORT).show();
                        }
                    }
                }


            });


        }

    }

}

